package com.ppp.poi.bean.base;

import com.ppp.poi.bean.entity.BaseEntity;
import com.ppp.poi.bean.enumeration.RES_STATUS;
import com.ppp.poi.common.exception.AppException;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.common.Mapper;

/**
 * @author Wu Jin
 * @create 2019-08-02
 */
@Slf4j
public class BaseService<T extends BaseEntity, D extends Mapper<T>> {

  @Autowired
  protected D dao;

  public int insert(T record) {
    try {
      int result = dao.insertSelective(record);
      return result;
    } catch (Exception e) {
      log.error("insert error record={}", record, e);
      throw new AppException(RES_STATUS.DB_ERROR);
    }
  }

  public int update(T record) {
    try {
      int result = dao.updateByPrimaryKeySelective(record);
      return result;
    } catch (Exception e) {
      log.error("update error record={}", record, e);
      throw new AppException(RES_STATUS.DB_ERROR);
    }
  }

  public int save(T record) {
    if (record.getId() == null || record.getId() == 0) {
      return insert(record);
    } else {
      return update(record);
    }
  }

  public T selectById(Object id) {
    try {
      T t = dao.selectByPrimaryKey(id);
      if (t == null) {
        throw new AppException(RES_STATUS.RESOURCE_NOT_EXIST);
      }
      return t;
    } catch (AppException e) {
      log.error("selectById error id={},", id, e);
      throw e;
    } catch (Exception e) {
      log.error("selectById error id={},", id, e);
      throw new AppException(RES_STATUS.DB_ERROR);
    }
  }

  public List<T> select(T record) {
    try {
      return dao.select(record);
    } catch (Exception e) {
      log.error("select error record={}", record, e);
      throw new AppException(RES_STATUS.DB_ERROR);
    }
  }

}
